package learn.baidu;

import cn.hutool.core.lang.Console;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONObject;
import learn.testenum.ImageLocationType;
import learn.testenum.LocationType;
import learn.testenum.TempletaType;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import static utils.Utils.*;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author 宋贤坤
 * @date 2019/5/9 13:33
 */
public class Sample {

    private static final String RET = "ret";
    private static final String TEMPLATE_SIGN = "templateSign";

    private static final String APP_ID = "16209766";
    private static final String API_KEY = "aYyRirHsG8bURQiphYyQv5Zl";
    private static final String SECRET_KEY = "8RIn5xE7fgcTfpQxLl4exQd8LbMVYVE6";

    public static void main(String[] args) throws Exception {

        List<OnlyWord> sample = sample(LocationType.BASE64, TempletaType.TEMPLATE_SIGN_HORIZONTAL_2, ImageLocationType.IMG_PATH_HORIZONTAL_3.getAddr());
        System.out.println(sample.get(3).getWord());
        Console.error(com.alibaba.fastjson.JSONObject.toJSONString(sample));
    }

    private static List<OnlyWord> sample(LocationType locationType, TempletaType templetaType, String imgPath) throws Exception {
        List<OnlyWord> onlyWords;
        HashMap<String, String> options = new HashMap(1);
        options.put(TEMPLATE_SIGN, templetaType.getTempletaId());
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        client.setSocketTimeoutInMillis(60000);
        client.setConnectionTimeoutInMillis(2000);
        byte[] dataByte = null;
        if (LocationType.BASE64.equals(locationType)) {
            String base64 = imageToBase64(imgPath);
            dataByte = base64ToImageBytes(base64);
        }
        if (LocationType.URL.equals(locationType)) {
            URL url = new URL(imgPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(2000);
            InputStream inStream = conn.getInputStream();
            dataByte = readInputStream(inStream);
        }
        String baiDuResult = client.custom(dataByte, templetaType.getTempletaId(), options).toString();
        JSONObject firstObject = new JSONObject(baiDuResult);
        String data = firstObject.get("data").toString();
        JSONObject secondObject = new JSONObject(data);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
        if (!jsonObject.containsKey(RET)) {
            return null;
        } else {
            String ret = secondObject.get(RET).toString();
            JSONArray array = JSONUtil.parseArray(ret);
            onlyWords = array.toList(OnlyWord.class);
        }
        return onlyWords;
    }
}

